<?php
/**
 * Created by PhpStorm.
 * User: Yangxufeng
 * Date: 2018-09-21
 * Time: 10:38
 */

namespace app\index\controller;

use app\index\server\OrderServer;
use app\model\OrderModel;
use app\model\ProductInfoModel;
use think\Db;
use app\index\model\M;
use think\cache\driver\Redis;
use app\index\server\MyselfServer;
use app\model\UserModel;

class Order extends Auth
{

    protected $suffix;

    static private $result = [
        'code' => 400,
        'info' => 'Parameter error',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new M();
        $this->suffix = substr($this->uid, -1, 1);
    }

//    public function index()
//    {
//        $orderServer = new OrderServer();
//        $orderList = $orderServer->getOrderList($this->uid);
//        $this->assign('orderList', $orderList);
//        return $this->fetch();
//    }
//
//    public function un_pay()
//    {
//        $type = (int)input('get.type') ? (int)input('get.type') : 1;
//        $mark = (new UserModel())->getValue("id = {$this->uid}", "is_vip");
//        $orderNum = (new OrderModel('', 'id desc', 0))->selectAll("user_id = {$this->uid} and status = {$type}", "id, order_no");
//        if ($orderNum) {
//            $orderStr = implode(array_unique(array_column($orderNum, 'id')), ',');
//            $orderInfo = (new OrderModel('sy_order_product', 'op.id desc', '', 'sy_product_info pi', 'op.product_id =  pi.id', '', 'op'))->selectAll("op.order_id in({$orderStr})", "pi.product_id, pi.name,  pi.price, pi.member_price,pi.color,pi.size,pi.url,op.order_id,op.num");
//            foreach ($orderNum as $key => $value) {
//                foreach ($orderInfo as $k => $v) {
//                    if ($value['id'] == $v['order_id']) {
//                        $orderNum[$key]['data'][] = $v;
//                    }
//                }
//            }
//            $this->assign('mark', $mark);
//            $this->assign('orderList', $orderNum);
//            return $this->fetch('order/index');
//        }
//        return $this->fetch('order/order_empty');
//    }
//
//    public function un_pay_json()
//    {
//        $limit = (int)input('get.limit') ? (int)input('get.limit') : 1;
//        $orderNum = (new OrderModel('', 'id desc', $limit))->selectAll("user_id = {$this->uid} and status = {$type}", "id, order_no");
//        if ($orderNum) {
//            $orderStr = implode(array_unique(array_column($orderNum, 'id')), ',');
//            $orderInfo = (new OrderModel('sy_order_product', 'op.id desc', '', 'sy_product_info pi', 'op.product_id =  pi.id', '', 'op'))->selectAll("op.order_id in({$orderStr})", "pi.product_id, pi.name,  pi.price, pi.member_price,pi.color,pi.size,pi.url,op.order_id,op.num");
//            foreach ($orderNum as $key => $value) {
//                foreach ($orderInfo as $k => $v) {
//                    if ($value['id'] == $v['order_id']) {
//                        $orderNum[$key]['data'][] = $v;
//                    }
//                }
//            }
//            return json_encode($orderNum);
//        }
//    }
//
//    public function already_pay()
//    {
//        $type = (int)input('get.type') ? (int)input('get.type') : 2;
//        $mark = (new UserModel())->getValue("id = {$this->uid}", "is_vip");
//        $orderNum = (new OrderModel('', 'id desc', 0))->selectAll("user_id = {$this->uid} and status = {$type}", "id, order_no");
//        if ($orderNum) {
//            $orderStr = implode(array_unique(array_column($orderNum, 'id')), ',');
//            $orderInfo = (new OrderModel('sy_order_product', 'op.id desc', '', 'sy_product_info pi', 'op.product_id =  pi.id', '', 'op'))->selectAll("op.order_id in({$orderStr})", "pi.product_id, pi.name,  pi.price, pi.member_price,pi.color,pi.size,pi.url,op.order_id,op.num");
//            foreach ($orderNum as $key => $value) {
//                foreach ($orderInfo as $k => $v) {
//                    if ($value['id'] == $v['order_id']) {
//                        $orderNum[$key]['data'][] = $v;
//                    }
//                }
//            }
//            $this->assign('mark', $mark);
//            $this->assign('orderList', $orderNum);
//            return $this->fetch('order/index');
//        }
//        return $this->fetch('order/order_empty');
////		$limit = (int)input('param.limit') ? (int)input('param.limit') : 0;
////		$orderServer = new OrderServer();
////		$orderList = $orderServer->getOrderList($this->uid, 2, $limit, 6);
////		$this->assign('orderList', $orderList);
////		return $this->fetch('order/index');
//    }
//
//    /**
//     * @var  配送重
//     */
//    public function to_address()
//    {
//        $limit = (int)input('param.limit') ? (int)input('param.limit') : 0;
//        $orderServer = new OrderServer();
//        $orderList = $orderServer->getOrderList($this->uid, 3, $limit, 6);
//
//        $this->assign('orderList', $orderList);
//        return $this->fetch('order/index');
//    }

//    public function already_receive()
//    {
//        $limit = (int)input('param.limit') ? (int)input('param.limit') : 0;
//        $orderServer = new OrderServer();
//        $orderList = $orderServer->getOrderList($this->uid, 8, $limit, 6);
//        $this->assign('orderList', $orderList);
//        return $this->fetch('order/index');
//    }

    public function delete()
    {
        $oid = (int)input('get.oid') ? (int)input('get.oid') : 0;
        if ($oid > 0) {
            $id = (new OrderServer())->deleteOne("id = " . (int)$oid . " and user_id = {$this->uid} and  status = 1");
            if ($id) {
                $result['code'] = 200;
                $result['info'] = '删除成功!';
            } else {
                $result['code'] = 202;
                $result['info'] = '删除失败!';
            }
            return json_encode($result);
        }
    }

    /**
     * @var 删除已使用优惠券
     */
    public function delcoupon($coupon)
    {
        $result = Db::table('sy_coupon')->delete($coupon);
    }

    /**
     * @var 订单
     */
    public function status($status)
    {
        if ($status < 8 && $status > 0) {
            $limit = (int)input('get.limit') ? (int)input('get.limit') : 0;
            $list = (new OrderModel($this->suffix, 'o.id desc', $limit, 'sy_order_info_' . $this->suffix . ' oi', 'oi.order_id = o.id', '', 'o'))->getOrder("uid = {$this->uid} and ostate = '{$status}'", 'o.id, o.order_num, o.deal_price, oi.pid, oi.num, oi.gid, oi.oprice, pi.name, pi.url, pi.color, pi.size');
            if ($limit) {
                return json_encode($list);
            }
            if ($list) {
                $this->assign('orderList', $list);
                return $this->fetch('order/index');
            } else {
                return $this->fetch('order/order_empty');
            }
        }
        return json_encode(self::$result);
    }

    /**
     *  @var 确认订单
     */
    public function quer()
    {
        $orderNum = input('get.order_num');
        // var_dump($orderNum);die;
        if ($orderNum && $this->uid) {
            $result = (new OrderModel($this->suffix))->updateOne("uid = {$this->uid} and order_num = '{$orderNum}'", ['ostate'=>'3']);
        }
    }

    /**
     * @var 未支付
     */
    public function unpaid()
    {
        $limit = (int)input('get.limit') ? (int)input('get.limit') : 0;
        $unPayStr = (new Redis())->get('unpaid_' . $this->uid);
        if ($unPayStr) {
            $unPayArr = self::_getUnPayArr(explode(',', $unPayStr), $limit, 6);
            if ($unPayArr) {
                $list = self::_checkArr($unPayArr, $this->uid);
                $list = $this->my_array_column($list);
                if (!empty($list['str'])) {
                    $info = (new ProductInfoModel())->selectAll("id in ({$list['str']})", 'id,url,name,color,size');
                    unset($list['str']);
                    $newInfo = [];
                    foreach ($info as $k => $v) {
                        $newInfo[$v['id']] = $v;
                    }
                    foreach ($list as $k => $v) {
                        foreach ($v as $key => $value) {
                            $list[$k][$key]['url'] = $newInfo[$value['pid']]['url'];
                            $list[$k][$key]['name'] = $newInfo[$value['pid']]['name'];
                            $list[$k][$key]['color'] = $newInfo[$value['pid']]['color'];
                            $list[$k][$key]['size'] = $newInfo[$value['pid']]['size'];
                        }
                    }
                    return $this->fetch('index1', ['orderList' => $list]);
                }
            }
        }
        if (!$limit) {
            return $this->fetch('order_empty');
        } else {
            return json_encode([]);
        }
    }

    /**
     * @var 获取limit只中的订单
     */
    static private function _getUnPayArr($arr, $limit, $length)
    {
        $offset = $limit * $length;
        $newArr = [];
        for ($i = $offset; $i < $length + 1; $i++) {
            if (!empty($arr[$i])) {
                $newArr[$i] = $arr[$i];
            } else {
                break;
            }
        }
        return $newArr;
    }

    /**
     * @var 获取订单详情并删除过期订单
     */
    static private function _checkArr($unPayArr = [], $id)
    {
        $newArr = [];
        $newStr = '';
        $redis = (new Redis());
        foreach ($unPayArr as $k => $v) {
            $result = $redis->get($v);
            if ($result && time() - $result['time'] < 15 * 60 - 1) {
                if ($newStr) {
                    $newStr .= ",{$result['order']['order_num']}";
                } else {
                    $newStr = $result['order']['order_num'];
                }
                $newArr[$k] = $result;
            }
        }
        (new Redis())->set('unpaid_' . $id, $newStr);
        return $newArr;
    }

    /**
     * @var 取出未支付订单中所有的商品及pid字符串
     */
    static private function my_array_column($arr)
    {
        $newArr = [];
        $str = '';
        foreach ($arr as $k => $v) {
            $newArr[$v['order']['order_num']] = $v['info']['goods'];
            if (!$str) {
                $str .= join(',', array_column($v['info']['goods'], 'pid'));
            } else {
                $str .= ',' . join(',', array_column($v['info']['goods'], 'pid'));
            }
        }
        $newArr['str'] = $str;
        return $newArr;
    }

    /**
     * @var 物流查询
     */
    public function express($oid)
    {
        if ((int)$oid && $this->suffix) {
            $expressInfo = (new OrderModel($this->suffix))->findOne("id = {$oid}", 'express_num, express_name');
            if ($expressInfo['express_num']) {
                $result = Express::getExpress($expressInfo['express_num'], $expressInfo['express_name']);
                if ($result) {
                    self::$result = [
                        'code' => 200,
                        'info' => $result,
                    ];
                }
            }
        }
        return json_encode(self::$result);
    }


    /**
     * @var 去支付
     */
    public function pay($order)
    {
        $orderInfo = (new Redis())->get($order);
        if ($orderInfo && $orderInfo['order']['uid'] == $this->uid) {
            return $this->redirect('/cart/pay?goodslist=' . json_encode($orderInfo['info']['goods']));
        }
        return json_encode(self::$result);
    }
}
